import datetime
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import base64
import re


class aesEndecode:
    iv = "jskey_1618823712"
    key = "6f4ff1fc2b53b9ee"

    def encrypt_aes(self, text):
        iv = self.iv.encode("utf8")
        key = self.key.encode("utf8")
        _aes = AES.new(key, AES.MODE_CBC, iv)
        en_text_encode = text.encode("utf8")
        en_text = _aes.encrypt(en_text_encode)
        # print(en_text.decode("utf-8", "ignore"))
        # return en_text.hex()
        return base64.b64encode(en_text).decode()

    def decrypt_aes(self, en_text):
        # en_text = bytes.fromhex(en_text)
        en_text = base64.b64decode(en_text)
        iv = self.iv.encode("utf8")
        key = self.key.encode("utf8")
        aes = AES.new(key, AES.MODE_CBC, iv)
        result = aes.decrypt(en_text)
        return result.decode()


class AesEncodePassword(aesEndecode):
    def encrypt_password(self, password: str):
        """
        加密六位数密码
        """
        reg = r'^\d{6}$'
        p = re.compile(reg)
        now = datetime.datetime.now().timestamp()
        now_timestamp = str(now)[0:10]
        if p.match(password):
            return self.encrypt_aes(password + now_timestamp)
        else:
            raise ValueError("密码必须为六位数字")

    def decrypt_password(self, en_text: str):
        """
        解密密码
        """
        password_str = self.decrypt_aes(en_text)
        return password_str[0:6]


# 将原始的明文用空格填充到16字节
def pad(data):
    pad_data = data
    for i in range(0, 16 - len(data)):
        pad_data = pad_data + ' '
    return pad_data
